import md5 from 'js-md5'
import Vue from 'vue'
import qs from 'qs'

class HttpData {
  constructor(params) {
    this.params = params
  }

  getWrapData() {
    let time = new Date().getTime()
    this.params['t'] = time + parseInt(Vue.cookie.get('timeDiff') || 0)
    this.params['token'] = Vue.cookie.get('token') || ''
    this.params['nonce'] = parseFloat(Math.random() * 0.3 + 1, 10).toFixed(10) * 1e10
    this.params['sign'] = this.getSign(this.params)
    return qs.stringify(this.params)
  }

  getSign(params) {
    var sign = ''
    var dataArray = []
    var keys = Object.keys(params)
    keys.sort().forEach(key => {
      let val = this.getVal(params[key])
      if (val && val.length > 0) {
        dataArray.push(key + '=' + val)
      }
    })
    dataArray.push('secret=' + Vue.cookie.get('secret'))
    var signStr = dataArray.join('&')
    sign = md5(signStr).toUpperCase()
    return sign
  }

  getVal(anyObj) {
    if (anyObj === undefined || anyObj === null) {
      return null
    }

    if (typeof anyObj === 'string') {
      return anyObj.trim()
    }

    if (typeof anyObj === 'number') {
      return anyObj.toString()
    }

    if (typeof anyObj === 'boolean') {
      return anyObj ? 'true' : 'false'
    }

    return anyObj
  }
}

export default HttpData
